import 'package:flutter/material.dart';
import 'package:get/get.dart';

/// https://www.jianshu.com/p/3a6ad16614ea
class SampleGetXHome extends StatefulWidget {
  const SampleGetXHome({Key? key}) : super(key: key);

  @override
  _SampleGetXHomeState createState() => _SampleGetXHomeState();
}

class _SampleGetXHomeState extends State<SampleGetXHome> {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      home: Demo1(),
    );
  }
}

class Demo1 extends StatelessWidget {
  Demo1({Key? key}) : super(key: key);

  /// 3种声明变量方式
  // RxInt count = RxInt(0);
  // var count = Rx<int>(0);
  var count = 0.obs;

  @override
  Widget build(BuildContext context) {
    var people1 = People.newBuild("tst1".obs, 33.obs);
    var people2 = People(name: RxString("test"), age: RxInt(18)).obs;
    return Scaffold(
      appBar: AppBar(
        title: Text("GetX基本使用"),
        centerTitle: true,
      ),
      body: SingleChildScrollView(
        child: Container(
            padding: EdgeInsets.only(left: 10, right: 10),
            child: ListView(
              shrinkWrap: true,
              children: [
                /// 用Obx包装需要使用的widget
                Obx(() => Text(
                      "count的值为: $count",
                      style: TextStyle(color: Colors.redAccent, fontSize: 20),
                    )),
                ElevatedButton(
                    onPressed: () {
                      count++;
                    },
                    child: Text("点击count++")),
                SizedBox(
                  height: 15,
                ),
                Obx(() => Text(
                      "person-1: name: ${people1.firstName.value} , age: ${people1.firstAge.value}",
                      style: TextStyle(color: Colors.redAccent, fontSize: 20),
                    )),
                ElevatedButton(
                    onPressed: () {
                      people1.firstName.value = "tst335";
                      people1.firstAge.value = 24;
                    },
                    child: Text("修改Person数据")),
                SizedBox(
                  height: 15,
                ),
                Obx(() => Text(
                      "person-2: name: ${people2.value.name} , age: ${people2.value.age}",
                      style: TextStyle(color: Colors.redAccent, fontSize: 20),
                    )),
                ElevatedButton(
                    onPressed: () {
                      // 数据不更新
                      people2.value.name = "tst337";
                      people2.value.age = 36;
                      // people2 = People(name: "tst337", age: 35).obs;
                    },
                    child: Text("修改Person-2数据('有bug，数据不更新')"))
              ],
            )),
      ),
    );
  }
}

class People {
  // 第一种：直接声明变量
  var firstName = "test".obs;
  var firstAge = 18.obs;

  var name;
  var age;

  People({this.name, this.age});

  People.newBuild(this.firstName, this.firstAge);
}
